{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# C++ 调用 Python"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于 {class}`~tvm.runtime.PackedFunc` 可以接受另一个 {class}`~tvm.runtime.PackedFunc` 作为参数，因此可以将 Python 中的函数（作为 {class}`~tvm.runtime.PackedFunc`）传递给 C++。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "````{tab-set-code}\n",
    "```{literalinclude} cpp/python_ext/src/tvm_ext.cc\n",
    ":language: c++\n",
    "```\n",
    "\n",
    "```{literalinclude} cpp/python_ext/Makefile\n",
    ":language: Makefile\n",
    "```\n",
    "````"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "rm -rf outputs/*\n",
      "g++ -std=c++17 -O2 -fPIC -I/media/pc/data/lxw/ai/tvm/include -I/media/pc/data/lxw/ai/tvm/3rdparty/dmlc-core/include -I/media/pc/data/lxw/ai/tvm/3rdparty/dlpack/include -Iinclude -DDMLC_USE_LOGGING_LIBRARY=\\<tvm/runtime/logging.h\\> -shared -o outputs/libs/libtvm_ext.so src/tvm_ext.cc -ldl -pthread -L/media/pc/data/lxw/ai/tvm/build\n"
     ]
    }
   ],
   "source": [
    "%%bash\n",
    "cd cpp/python_ext\n",
    "make clean\n",
    "make"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world\n"
     ]
    }
   ],
   "source": [
    "import tvm\n",
    "from tvm_book.tvm_ext.libinfo import load_lib\n",
    "_LIB_EXT, _LIB_EXT_NAME = load_lib(name=\"libtvm_ext.so\", search_path=[\"cpp/python_ext/outputs/libs\"])\n",
    "\n",
    "def callback(msg):\n",
    "  print(msg)\n",
    "\n",
    "# convert to PackedFunc\n",
    "f = tvm.runtime.convert(callback)\n",
    "callhello = tvm.get_global_func(\"callhello\")\n",
    "# prints hello world\n",
    "callhello(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ai",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
